package com.bulletelc.apollopre.wxapi;


import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.eventbus.WeChatEntryEventBus;
import com.bulletelc.apollopre.utils.LogUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * author: lhl
 * date  : 2017/11/07
 * desc  : 接收微信的请求及返回值
 * 微信分享等的回调
 */
public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI iwxapi;

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iwxapi = MyApplication.getInstance().getIwxapi();
        iwxapi.handleIntent(getIntent(), this);
    }

    /**
     * 微信发送的请求将回调到onReq方法
     *
     * @param baseReq
     */
    @Override
    public void onReq(BaseReq baseReq) {
        LogUtil.i("openId=" + baseReq.openId +
                "\ntype=" + baseReq.getType() +
                "\ntransaction=" + baseReq.transaction +
                "\ncheckArgs=" + baseReq.checkArgs() +
                "\ntoString=" + baseReq.toString()
        );

    }

    /**
     * 发送到微信请求的响应结果将回调到onResp方法
     *
     * @param baseResp
     */
    @Override
    public void onResp(BaseResp baseResp) {
//        LogUtil.i("openId=" + baseResp.openId +
//                "\ntype=" + baseResp.getType() +
//                "\ntransaction=" + baseResp.transaction +
//                "\ncheckArgs=" + baseResp.checkArgs() +
//                "\nerrCode=" + baseResp.errCode +
//                "\nerrStr=" + baseResp.errStr +
//                "\ntoString=" + baseResp.toString()
//        );

        WeChatEntryEventBus event = new WeChatEntryEventBus();
        event.setBaseResp(baseResp);
        EventBus.getDefault().post(event);
        finish();

    }

    /**
     * 获取access_token
     *
     * @param code
     */
    public void getAccessToken(final String code) {
        final Map<String, Object> params = new HashMap<>();
        params.put("appid", GlobalConfig.WX_API_APP_ID);
        params.put("secret", GlobalConfig.WX_API_KEY);
        params.put("code", code);
        params.put("grant_type", "client_credential");
        OkGo.<String>get("https://api.weixin.qq.com/sns/oauth2/access_token?")
                .params("appid", GlobalConfig.WX_API_APP_ID)
                .params("secret", GlobalConfig.key)
                .params("code", code)
                .params("grant_type", "authorization_code")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtil.i(response.body().toString());
                        paramsData(response);
                    }
                });

    }

    public void paramsData(Response<String> response) {
        if (response.isSuccessful()) {
            try {
                JSONObject jsonObject = new JSONObject(response.body().toString());
                String accessToken = jsonObject.getString("access_token"); //保存access_token，2小时有效，下次直接用
                String openid = jsonObject.getString("openid");
                String unionid = jsonObject.getString("unionid");
                getUserInfo(accessToken, openid, unionid);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取微信用户授权信息
     *
     * @param access_token
     * @param openid
     * @param unionid
     */
    public void getUserInfo(final String access_token, final String openid, final String unionid) {
        OkGo.<String>get("https://api.weixin.qq.com/sns/userinfo")
                .params("access_token", access_token)
                .params("openid", openid)
                .params("unionid", unionid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtil.i(response.body().toString());
                    }
                });
    }

}
